package life.majiang.community.provider;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import life.majiang.community.dto.AccessTokenDTO;
import life.majiang.community.dto.GitHubUser;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Component
public class GitHubProvider {
	
	@Value("${github.access.token.url}")
	private String accessTokenUrl;
	
	@Value("${github.api.user.url}")
	private String apiUserUrl;
	
	private static final String ACCEPT_KEY = "Accept";
	private static final String ACCEPT_VALUE = "application/json; charset=utf-8";
	
	public String getAccessToken(AccessTokenDTO accessTokenDTO) {
		ObjectMapper mapper = new ObjectMapper();
		OkHttpClient client = new OkHttpClient();
		MediaType mt = MediaType.get(ACCEPT_VALUE);
		try {
			RequestBody getAccessTokenBody = RequestBody.create(mt, mapper.writeValueAsString(accessTokenDTO));
			Request getAccessTokenRequest = new Request.Builder()
					.url(accessTokenUrl)
					.addHeader(ACCEPT_KEY, ACCEPT_VALUE)
					.post(getAccessTokenBody).build();
			Response getAccessTokenResponse = client.newCall(getAccessTokenRequest).execute();
			return (String) mapper.readValue(getAccessTokenResponse.body().string(), Map.class).get("access_token");
		} catch (IOException e) {
		}
		return null;
	}
	
	public GitHubUser getUser(String accessToken) {
		ObjectMapper mapper = new ObjectMapper();
		OkHttpClient client = new OkHttpClient();
		Request userReq = new Request.Builder()
				.url(apiUserUrl)
				.addHeader(ACCEPT_KEY, ACCEPT_VALUE)
				.addHeader("Authorization", "token " + accessToken).build();
		try {
			Response userRes = client.newCall(userReq).execute();
			return mapper.readValue(userRes.body().string(), GitHubUser.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
